#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import logging
#logging.basicConfig(level=logging.INFO)
logging.basicConfig(filename='xgits.log', filemode="w", level=logging.INFO)
mylogger=logging.getLogger()
mylogger.addHandler(logging.StreamHandler())
import pdb
import sys
import  shutil 
from git import Repo
import common_operation
import my_git
import  xml.dom.minidom
import os
import logging
import mx_git_project

'这个是冯秀伟专用的python工具库'
__author__='fengxw'

this_file_path_ = os.path.split(os.path.realpath(__file__))[0]
logging.info('this py file in this path:'+this_file_path_)

mx_git_projects = []


def all_git_path():
	lists=[]
	lists = common_operation.find_dir_father_path(os.path.abspath('.'),'.git')
	lists = common_operation.clear(lists , 'mxrepo')
	lists = common_operation.clear(lists , 'repo')
	lists = common_operation.clear(lists , 'manifests')
	return lists

def all_git_repo():
	pathAndRepos = []
	git_paths = all_git_path()
	for git_path in git_paths:
		myrepo = Repo(git_path)
		pathAndRepos.append([git_path , myrepo])
	return pathAndRepos

def recover():
	target_xml_path = this_file_path_ +'/.mxrepo/manifests/default.xml'
        if False == os.path.exists(target_xml_path):
            target_xml_path = this_file_path_ +'/.repo/manifests/default.xml'

	mx_git_projects = inflate_xml(target_xml_path)

	for proj_item in mx_git_projects:
		logging.info("in "+proj_item.get_path()+": {")
		logging.info("cmd: recover")
		logging.info(my_git.checkout_only(proj_item.get_repo() , proj_item.get_branch()))
		logging.info("}")
	pass

def inflate_xml(xml_path):
	global this_file_path_
	logging.info('prasexml start :'+xml_path)
	#pdb.set_trace()
	dom = xml.dom.minidom.parse(xml_path)
	root = dom.documentElement
	nodes = root.childNodes
	logging.info(' nodes cnt:'+str(len(nodes)))
	for node in nodes:
		if('project' == node.nodeName):
			path = node.getAttribute('path')
			name = node.getAttribute('name')
			branch = node.getAttribute('branch')
			revision = node.getAttribute('revision')
			pre_revision = node.getAttribute('pre_revision')
			git_project = mx_git_project.mx_git_project(path ,name , branch , revision , pre_revision)
			git_project.generate_repo(this_file_path_)
			#logging.info(' path:'+git_project.get_path()+' name:'+git_project.get_name()+' branch:'+git_project.get_branch()+' revision:'+git_project.get_revision()+' pre_revision:'+git_project.get_pre_revision() + ' repo:'+str(git_project.get_repo()))
			mx_git_projects.append(git_project)
	logging.info(' mx_git_projects cnt:'+str(len(mx_git_projects)))

	logging.info('prasexml end ---->')
	return mx_git_projects

def run_on_all_repo( cmd , cmd1=0 ,cmd2=0 ):
	pathAndRepos = all_git_repo()
	for item in pathAndRepos:
		if cmd == '-branch': 
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git branch")
			logging.info(my_git.active_branch( item[1] ).name )
			logging.info("}")
		elif cmd == '-show_all':
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git branch -a")
			logging.info(my_git.show_all( item[1] ))
			logging.info("}")
		elif cmd == '-is_dirty':
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git status")
			logging.info(my_git.is_dirty( item[1] ))
			logging.info("}")
		elif cmd == '-clear':
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git checkout .")
			logging.info(my_git.clear_with_checkout( item[1] ))
			logging.info("}")
		elif cmd == '-pull':
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git pull")
			logging.info(my_git.pull( item[1] ))
			logging.info("}")
		elif cmd == '-fetch':
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git fetch")
			logging.info(my_git.fetch_only( item[1] ))
			logging.info("}")
		elif cmd == '-cb':
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git branch "+cmd1)
			logging.info(my_git.create_branch_from_current_branch( item[1] , cmd1 ))
			logging.info("}")
		elif cmd == '-db':
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git branch -d "+cmd1)
			logging.info(my_git.delete_branch( item[1] ,cmd1))
			logging.info("}")
		elif cmd == '-sbs':
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git checkout "+cmd1+" soft ,if not have,create it")
			logging.info(my_git.switch_branch_soft( item[1] , cmd1))
			logging.info("}")
		elif cmd == '-sbf':
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git checkout "+cmd1+" force,if not have,create it")
			logging.info(my_git.switch_branch_force( item[1] , cmd1))
			logging.info("}")
		elif cmd == '-checkout':
			logging.info("in "+item[0]+": {")
			logging.info("cmd:git checkout "+cmd1+" only")
			logging.info(my_git.checkout_only( item[1] , cmd1))
			logging.info("}")



#=================test code =================================================
if __name__=='__main__':
	logging.info('argv is:')
	logging.info(sys.argv)
	if sys.argv[1] in [ '-branch' , '-show_all' , '-is_dirty','-clear','-pull','-fetch' ]:
		run_on_all_repo( sys.argv[1] )
	elif sys.argv[1] in ['-cb','-db','-sbs','-sbf' ,'-checkout']:
		run_on_all_repo(sys.argv[1] ,  sys.argv[2] )
	elif ('-recover' == sys.argv[1]):
		recover()
